package com.community.backend.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.community.backend.pojo.Visitor;
import com.community.backend.pojo.dto.VisitorLeaveDTO;
import com.community.backend.pojo.dto.VisitorQueryDTO;
import com.community.backend.service.VisitorService;
import com.community.backend.utils.PageResult;
import com.community.backend.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/visitor")
@Slf4j
public class VisitorController {
    private final VisitorService visitorService;

    public VisitorController(VisitorService visitorService) {
        this.visitorService = visitorService;
    }

    @RequestMapping("/page")
    public Result<PageResult>  page(VisitorQueryDTO visitorQueryDTO) {
         PageResult pageResult = visitorService.pageQuery(visitorQueryDTO);
        return Result.success(pageResult);
    }
    @PostMapping
    public Result save(@RequestBody Visitor visitor){
        visitor.setIsDelete("未删除");
        visitor.setLeave("未离开");
        System.out.println("保存访客信息："+visitor);
        visitorService.insert(visitor);
        return Result.success();
    }
//访客已离开
    @PutMapping("/leave")
    public Result leave(VisitorLeaveDTO visitorLeaveDTO){
        if (visitorLeaveDTO.getId() == null || visitorLeaveDTO.getId() <= 0 || visitorLeaveDTO.getId() > 1000000){
            return Result.error("参数错误");
        }
        Visitor visitor = new Visitor();
        BeanUtil.copyProperties(visitorLeaveDTO,visitor);
        visitor.setLeaveTime(String.valueOf(new DateTime()));
        visitor.setLeave("已离开");
        System.out.println("访客已离开："+visitor);
        visitorService.update(visitor);
        return Result.success();
    }
    @GetMapping("/{id}")
    public Result selectById(@PathVariable Integer id){
        Visitor visitor = visitorService.selectById(id);
        return Result.success(visitor);
    }
    @PutMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        visitorService.deleteById(id);
        return Result.success();
    }
    @PutMapping
    public Result update(@RequestBody Visitor visitor){
        visitorService.update(visitor);
        return Result.success();
    }
}
